package im.starchat.chat.utils;

import java.io.File;

import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * Description: 下载APK的管理类 <br/>
 */
public class DownloadApkManager {

    private static final String EXTERNAL_DIR = "StarChat";

    private static DownloadApkManager mApkManager = null;

    private DownloadCompleteReceiver receiver;

    private Context mContext = null;

    private DownloadManager downloadManager;

    public DownloadApkManager(Context mContext) {
        this.mContext = mContext;
    }

    public static DownloadApkManager getInstance(Context ctx) {
        if (null == mApkManager) {
            mApkManager = new DownloadApkManager(ctx);
        }
        return mApkManager;
    }

    private void regDownloadReceiver() {
        receiver = new DownloadCompleteReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        mContext.registerReceiver(receiver, filter);
    }

    /**
     * 调用DownloadManager下载最新的APK
     */
    @SuppressWarnings("deprecation")
    public void launchDownloadTool(String apkUrl, String appName) {
        if (!TextUtils.isEmpty(apkUrl)) {
            regDownloadReceiver();
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            Request down = new Request(Uri.parse(apkUrl));
            // 设置允许使用的网络类型，这里是移动网络和wifi都可以
             down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
             | DownloadManager.Request.NETWORK_WIFI);
//            down.setAllowedNetworkTypes(Request.NETWORK_WIFI);
            // 发出通知，即后台下载
            down.setShowRunningNotification(true);
            // 显示下载界面
            down.setVisibleInDownloadsUi(true);
            // 下载完成后也驻留在通知栏上
            down.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            if (isFolderExist(EXTERNAL_DIR)) {
                down.setDestinationInExternalPublicDir(EXTERNAL_DIR, appName + ".apk");
                try {
                    long reference = downloadManager.enqueue(down);// 下载对应的唯一标识
                    PreferencesStorageUtil.putDownloadId(mContext,reference);
                } catch (Exception e) {
                    Toast.makeText(mContext, "无法下载",
                            Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            Toast.makeText(mContext, "无法下载",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isFolderExist(String dir) {
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }


    // 接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(mContext, "下载完成",
                    Toast.LENGTH_SHORT).show();
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                DownloadManager dm = (DownloadManager) mContext
                        .getSystemService(Context.DOWNLOAD_SERVICE);
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                long downloadId = PreferencesStorageUtil.getDownloadId(mContext);
                if (id == downloadId) {
                    Uri uriForDownloadedFile = downloadManager.getUriForDownloadedFile(downloadId);
                    if (null != uriForDownloadedFile) {
                        Intent installIntent = new Intent(Intent.ACTION_VIEW);
                        installIntent.setDataAndType(uriForDownloadedFile,
                                "application/vnd.android.package-archive");
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(installIntent);
                    }
                }
            }
        }
    }

}

